using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WPF_MVVM_Test.MVVM_View.UserControl
{
    public partial class MesAiChat : System.Windows.Controls.UserControl
    {
        public MesAiChat()
        {
            InitializeComponent();
            
            // 订阅 DataContext 变更事件
            this.DataContextChanged += MesAiChat_DataContextChanged;
            
            // 订阅加载完成事件
            this.Loaded += MesAiChat_Loaded;
        }

        private void MesAiChat_Loaded(object sender, RoutedEventArgs e)
        {
            // 确保绑定到消息集合变更事件
            if (DataContext is MVVM_ViewModel.MesAiChatViewModel viewModel)
            {
                if (viewModel.ChatMessages is INotifyCollectionChanged notifyCollection)
                {
                    notifyCollection.CollectionChanged -= ChatMessages_CollectionChanged;
                    notifyCollection.CollectionChanged += ChatMessages_CollectionChanged;
                }
                
                // 强制刷新一次
                if (ChatItemsControl != null)
                {
                    ChatItemsControl.Items.Refresh();
                }
                ScrollToBottom();
            }
        }

        private void MesAiChat_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            // 如果之前有绑定，先解除绑定
            if (e.OldValue is MVVM_ViewModel.MesAiChatViewModel oldViewModel)
            {
                if (oldViewModel.ChatMessages is INotifyCollectionChanged oldNotifyCollection)
                {
                    oldNotifyCollection.CollectionChanged -= ChatMessages_CollectionChanged;
                }
            }

            // 绑定新的ViewModel
            if (e.NewValue is MVVM_ViewModel.MesAiChatViewModel newViewModel)
            {
                if (newViewModel.ChatMessages is INotifyCollectionChanged newNotifyCollection)
                {
                    newNotifyCollection.CollectionChanged += ChatMessages_CollectionChanged;
                }
            }
        }

        private void ChatMessages_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            // 当消息集合发生变化时，滚动到底部
            Dispatcher.BeginInvoke(new Action(() =>
            {
                ScrollToBottom();
            }), System.Windows.Threading.DispatcherPriority.Background);
        }

        private void ScrollToBottom()
        {
            try
            {
                if (ChatScrollViewer != null)
                {
                    ChatScrollViewer.ScrollToEnd();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"滚动到底部时发生错误: {ex.Message}");
            }
        }

        private void MessageTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                // 检查是否按下了Shift键
                if (Keyboard.Modifiers == ModifierKeys.Shift)
                {
                    // Shift+Enter：换行，不发送消息
                    return;
                }
                
                // 单独按Enter：发送消息
                if (DataContext is MVVM_ViewModel.MesAiChatViewModel viewModel)
                {
                    if (viewModel.SendMessageCommand.CanExecute(null))
                    {
                        viewModel.SendMessageCommand.Execute(null);
                        e.Handled = true; // 阻止默认的Enter行为
                    }
                }
            }
        }
    }
}
